package com.to8to.autotask.heartbeat;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Arrays;
import java.util.List;

import org.elasticsearch.common.collect.Lists;
import org.elasticsearch.index.query.FilterBuilders;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.to8to.autotask.util.DBUtil;
import com.to8to.es.dao.ESTypes;
import com.to8to.es.dao.ESUtil;
import com.to8to.es.util.LogUtil;

/**
 * CustServicerOnline.java
 * 作 者：atom.liu
 * 版 本：v2.0
 * 日 期：2014年12月1日
 * 描 述：客服在线接口
 */
public class CustServicerOnline
{
    private static final String USER_INFO_SQL =
        "select uid,cityids from to8to_user_info where crmroleid = %s and cityids != '' and cityids is not null and isclose = 0";

    private static final Logger logger = LoggerFactory.getLogger(CustServicerOnline.class);

    /**
     * 维持客服在线的心跳方法
     * @param uid 客服id
     */
    public static void heartBeat(int uid)
    {
        ESUtil.es.save(ESTypes.TYPE_KFONLINE, String.format("{\"timestamp\": %s}", System.currentTimeMillis()), String.valueOf(uid));
    }

    /**
     * 获取在线客服列表 
     */
    public static List<Integer> getOnline()
    {
        //最近五分钟内在线的客服
        long stime = System.currentTimeMillis() - 5 * 60 * 1000L;
        String[] ids = ESUtil.es.searchIds(FilterBuilders.rangeFilter("timestamp").gt(stime), ESTypes.TYPE_KFONLINE);

        List<Integer> result = Lists.newArrayList();
        for (String id : ids)
        {
            try
            {
                result.add(Integer.parseInt(id));
            }
            catch (NumberFormatException e)
            {
                logger.error("getOnline() parseInt({}) error！{} \n {}", id, e, LogUtil.logStackTrace(e));
            }
        }
        return result;
    }

    /**
     * 获取用于分配的客服id
     * @param type 1家装顾问，2电商顾问
     * @param cityid 城市id
     */
    public static int getAllocateUser(int type, int cityid)
    {
        int roleid = type == 1 ? 15 : 12; //15家装顾问 12电商顾问
        String sql = String.format(USER_INFO_SQL, roleid);
        int result = -1;

        Connection connect = null;
        Statement stat = null;
        ResultSet rs = null;

        try
        {
            connect = DBUtil.getConnection();
            stat = connect.createStatement();
            rs = stat.executeQuery(sql);

            while (rs.next())
            {
                String cityids = rs.getString("cityids");
                List<String> cityIdList = Arrays.asList(cityids.split(","));
                if (cityIdList.contains(String.valueOf(cityid)))
                {
                    result = rs.getInt("uid");
                    break;
                }
            }
        }
        catch (Throwable e)
        {
            logger.error("获取需要分配的客服id异常！{} \n {}", e, LogUtil.logStackTrace(e));
        }
        finally
        {
            DBUtil.releaseSource(rs, stat, connect);
        }
        return result;
    }
}
